<?php

namespace App\Api\Controllers;


use Dingo\Api\Http\Request;
use Illuminate\Support\Facades\DB;

class PrizeDrawController extends BaseController
{
    public function getNumber(Request $request)
    {
        $code = $request->get('code');
//
//        $code = md5(rand(1,999).time());

        $info = DB::table('swt_prize') -> where('ip', $code) -> first();

        if(!$info) {
            DB::beginTransaction();
            try {
                $res = DB::table('swt_prize_config') -> where('id', 1) -> lockForUpdate() -> first();

                $max = $res -> count + 1;

                if($max === 400) {
                    $max = 500;
                }

                while(true) {
                    if(strpos($max, '4') === false) {
                        break;
                    }
                    $max++;
                }

                $data = [
                    'id'  => $max,
                    'ip'  => $code,
                    'key' => $code,
                    'created_at' => date('Y-m-d H:i:s', time())
                ];

                $id = DB::table('swt_prize') -> insertGetId($data);

                DB::table('swt_prize_config') -> where('id', 1) -> update(['count' => $max]);

                DB::commit();
            } catch(\Exception $e) {
                DB::rollBack();
            }
            $number = $id;
        } else {
            $number = $info -> id;
        }

        $format = '%03d';

        $result = sprintf($format, $number);

        return response()->json([
            'success' => true,
            'data' => [
                'number' => $result
            ]
        ]);
    }

    public function refresh(Request $request)
    {
        DB::table('swt_prize') -> delete();

        DB::table('swt_prize_config') -> where('id', 1) -> update(['count' => 0]);

        DB::statement("ALTER TABLE `swt_prize` AUTO_INCREMENT = 1");

        return response()->json([
            'success' => true
        ]);
    }

    public function getCount(Request $request)
    {
        $max = DB::table('swt_prize') -> max('id');
        $count = DB::table('swt_prize') -> count();

        return response()->json([
            'success' => true,
            'data' => [
                'number' => $count,
                'max'    => $max
            ]
        ]);
    }
}

